package com.zondy.mapgis.android.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption;
import com.umeng.socialize.UMShareAPI;
import com.zondy.mapgis.android.base.BaseFragment;
import com.zondy.mapgis.android.environment.Environment;
import com.zondy.mapgis.android.environment.Environment.AuthorizeCallback;
import com.zondy.mapgis.android.frag.AccountFrag;
import com.zondy.mapgis.android.frag.LayerManagerFragment;
import com.zondy.mapgis.android.frag.MapManagerModuleFrag;
import com.zondy.mapgis.android.frag.SearchModuleFrag;
import com.zondy.mapgis.android.frag.TracksHistoryFrag;
import com.zondy.mapgis.android.gpx.bean.Track;
import com.zondy.mapgis.android.graphic.GraphicCircle;
import com.zondy.mapgis.android.graphic.GraphicImage;
import com.zondy.mapgis.android.map.dao.ICallBack;
import com.zondy.mapgis.android.map.dao.ICallBackGoBack;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.mapview.MapView.MapViewFinishCallback;
import com.zondy.mapgis.android.mapview.MapView.MapViewMapLoadListener;
import com.zondy.mapgis.android.mapview.MapView.MapViewStopCurRequestCallback;
import com.zondy.mapgis.android.mapview.MapView.MapViewTouchListener;
import com.zondy.mapgis.android.model.EnumViewPos;
import com.zondy.mapgis.android.service.LocationService;
import com.zondy.mapgis.android.service.MyOrientationListener;
import com.zondy.mapgis.android.utils.AnimationsToolsUtils;
import com.zondy.mapgis.android.utils.BitmapCreator;
import com.zondy.mapgis.android.utils.CoordinateConvert;
import com.zondy.mapgis.android.utils.CoordinateConvertParameter;
import com.zondy.mapgis.android.utils.CoordinateType;
import com.zondy.mapgis.android.utils.DialogUtil;
import com.zondy.mapgis.android.utils.GPSUtil;
import com.zondy.mapgis.android.utils.MapLayerUtils;
import com.zondy.mapgis.android.utils.SharedUtils;
import com.zondy.mapgis.android.utils.StringUtils;
import com.zondy.mapgis.android.utils.SysEnv;
import com.zondy.mapgis.android.utils.ToolToast;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.core.geometry.Rect;
import com.zondy.mapgis.core.map.Map;
import com.zondy.mapgis.core.map.MapServer;
import com.zondy.mapgis.core.map.MapServerAccessMode;
import com.zondy.mapgis.core.map.MapServerType;
import com.zondy.mapgis.core.map.ServerLayer;
import com.zondy.mapgis.core.object.Enumeration;
import com.zondy.mapgis.core.spatial.SpaProjection;
import com.zondy.mapgis.core.srs.ElpTransParam;
import com.zondy.mapgis.core.srs.SRefData;
import com.zondy.mapgis.explorer.BaseMapActivity;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.explorer.R;
import com.zondy.mapgis.map.model.ConfigManager;
import com.zondy.mapgis.map.model.GPS;
import com.zondy.mapgis.map.model.MapInfo;

/**
 * 基本的地图Activity<br>
 * 使用了一套基础的可扩展的界面，实现了{@link BaseMapActivity}中所有接口，提供一组公用方法给其他模块调用。<br>
 * 创建时，自动加载一个默认地图或上一次打开的地图。
 * 
 * @author fjl
 */
public class MapActivity extends BaseMapActivity implements OnClickListener,MapViewTouchListener,MapViewMapLoadListener
{

	private String TAG = this.getClass().getSimpleName();
	public ConfigManager mConfigManager;
	public static int TracksRequestCode = 6;
	public MapView mMapView = null;
	private Map mServerMap = new Map();
	private MapInfo mMapInfo = new MapInfo();
	private ServerLayer mServerLayer = new ServerLayer();
	private List<BaseFragment> mfrags = new ArrayList<BaseFragment>();
	private boolean IsloadMapFinish = false;
	public SRefData mSRefData = null;
	/**
	 * 地图数据类型
	 */
	public static final int MAPX = 0;
	public static final int IGSERVER = 1;
	public static final int ONLINEMAP = 2;

	/**
	 * 定位状态
	 */
	public static int mLocationType = -1;
	public static int LOCATION_TYPE_LOCATE = 0;
	public static int LOCATION_TYPE_MAP_FOLLOW = 1;
	public static int LOCATION_TYPE_MAP_ROTATE = 2;

	/**
	 * 界面view
	 */
	public LinearLayout mTopContent = null;
	public LinearLayout mMapBottomContent = null;
	public RelativeLayout mFullcontent = null;
	public LinearLayout mMapRightContent = null;
	public RelativeLayout mComposerButtonsWrapper = null;
	public RelativeLayout mZoomLayout = null;
	private boolean mIsShowTools = true;

	ProgressDialog myDialog;
	private Bitmap mNorthArrowBmp = null;
	/**
	 * 定位相关
	 */
	public MyOrientationListener mMyOrientationListenr = null;
	private LocationService locationService;
	private LocationClientOption mOption = null;
	private float mCurrentRoateAngle = 0.0f;

	public ImageView mLocationImv = null;
	private boolean IsFirstClickLocation = true;
	private GraphicImage mLocationGraphicImage = null;
	private GraphicCircle mGraphicCircle = null;
	private Bitmap mLocationBmpOne = null;
	private Bitmap mLocationBmpTwo = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate() run!!");

		initView();
		// 在线服务图层添加到Map上
		mServerMap.append(mServerLayer);
		com.zondy.mapgis.android.environment.Environment.requestAuthorization(this, new AuthorizeCallback()
		{
			@Override
			public void onComplete()
			{
				initMap();
			}
		});

		Environment.updateAppVersion(this);
		// ServerUtil s = new ServerUtil(this);
		// ServerUtil.UpdateVersion1(this);
		MapApplication.getApp().setMapActivity(this);
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public void initView()
	{
		setContentView(R.layout.main);
		initMapView();
		// 透明状态栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		// 透明导航栏
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
		// setWindowStatusBarColor(this, R.color.main_color_two);

		mTopContent = (LinearLayout) find(R.id.maintop_content);
		mMapRightContent = (LinearLayout) findViewById(R.id.map_right_content);
		mMapBottomContent = (LinearLayout) findViewById(R.id.main_bootom);
		mFullcontent = (RelativeLayout) findViewById(R.id.full_content);
		mMapRightContent.setVisibility(View.VISIBLE);
		mLocationImv = (ImageView) findViewById(R.id.locationbtn_imgv);
		mComposerButtonsWrapper = (RelativeLayout) findViewById(R.id.composer_buttons_wrapper);
		mZoomLayout = (RelativeLayout) findViewById(R.id.zoom_layout);

		findViewById(R.id.changemap_iv).setOnClickListener(this);
		findViewById(R.id.check_layer_iv).setOnClickListener(this);
		findViewById(R.id.tools_channel).setOnClickListener(this);
		findViewById(R.id.more_channel).setOnClickListener(this);
		findViewById(R.id.map_search_channel).setOnClickListener(this);
		findViewById(R.id.zoomin_btn).setOnClickListener(this);
		findViewById(R.id.zoomout_btn).setOnClickListener(this);
		mLocationImv.setOnClickListener(this);
		// mLocationImv.setBackgroundResource(R.drawable.ico_location_1);
		mLocationImv.setBackground(getResources().getDrawable(R.drawable.ico_location_1));

		mNorthArrowBmp = BitmapCreator.fromAsset(this, "ico_northarrow_img.png");
		mLocationBmpOne = BitmapFactory.decodeResource(getResources(), R.drawable.ico_main_location);
		mLocationBmpTwo = BitmapFactory.decodeResource(getResources(), R.drawable.ico_main_location_two);

		// 初始化获取旋转方向角监听
		mMyOrientationListenr = new MyOrientationListener(getApplicationContext());
		mMyOrientationListenr.start();
		mMyOrientationListenr.setOnOrientationListener(new MyOrientationListener.OnOrientationListener()
		{
			@Override
			public void onOrientationChanged(float x)
			{
				mCurrentRoateAngle = x;
			}
		});

		/**
		 * 初始化并开启定位
		 */
		initLocation();
		locationService.start();// 定位SDK
	}

	/**
	 * 初始化MapView视图
	 * 
	 */
	private void initMapView()
	{
		mMapView = (MapView) findViewById(R.id.map_main);
		mConfigManager = mConfigManager.getInstance(getApplicationContext());

		mMapView.setZoomControlsEnabled(false);
		mMapView.setShowLogo(false);
		// mMapView.setNorthArrowImage(mNorthArrowBmp);
		// mMapView.setNorthArrowPosition(new PointF(SysEnv.SCREEN_WIDTH / 12 ,
		// SysEnv.SCREEN_HEIGHT / 10));
		mMapView.setNorthArrowPosition(new PointF(SysEnv.dip2px(this, 30), SysEnv.dip2px(this, 90)));
		mMapView.setScaleBarPoistion(new PointF(SysEnv.SCREEN_WIDTH / 15, SysEnv.SCREEN_HEIGHT * 5 / 6));
		// 定位图标
		if (mLocationGraphicImage == null)
		{
			mLocationGraphicImage = new GraphicImage();
			mLocationGraphicImage.setImage(mLocationBmpOne);
			mLocationGraphicImage.setPoint(new Dot(-2004026200000.0, -2004026200000.0));
			mLocationGraphicImage.setAnchorPoint(new PointF(0.5f, 0.5f));
			mLocationGraphicImage.setSlope(true);
		}
		if (mGraphicCircle == null)
		{
			mGraphicCircle = new GraphicCircle();
			// mGraphicCircle.setColor(Color.argb(38, 0, 0, 100));
			mGraphicCircle.setColor(getResources().getColor(R.color.location_circle_color));
			mGraphicCircle.setBorderlineColor(getResources().getColor(R.color.skyblue));
		}
		mMapView.getGraphicsOverlay().addGraphic(mLocationGraphicImage);
		mMapView.getGraphicsOverlay().addGraphic(mGraphicCircle);
		mMapView.setMapLoadListener(this);
		mMapView.setTouchListener(this);
	}

	@Override
	public void initMap()
	{
		IsloadMapFinish = false;
		mMapInfo = SharedUtils.getInstance().getMapInfo(getApplicationContext());
		int mapType = mMapInfo.getMapType();
		final String igServerAddress = mMapInfo.getIgserverAddress();
		mServerLayer.setAccessMode(MapServerAccessMode.ServerAndCache);
		mServerLayer.setAutoScaleFlag(true);

		if (mapType == MAPX && StringUtils.isNotEmpty(mMapInfo.getMapxPath()))
		{
			// 加载地图文档mapx
			mMapView.loadFromFileAsync(mMapInfo.getMapxPath());
			Log.d(TAG, "loadFromFile:" + mMapView.loadFromFile(mMapInfo.getMapxPath()));
		}
		else if (mapType == IGSERVER && StringUtils.isNotEmpty(mMapInfo.getIgserverAddress()))
		{
			mMapView.stopCurRequest(new MapViewStopCurRequestCallback()
			{
				@Override
				public void onDidStopCurRequest()
				{
					// 加载IGServer地图服务
					if (igServerAddress.contains("docs"))
					{
						// mServerLayer.setMapServerByType(MapServerType.MapGISIGSServerVector);
						MapServer mapServer = mServerLayer.createMapServerByType(MapServerType.MapGISIGSServerVector);
						mapServer.setName("docs");
						mServerLayer.setMapServer(mapServer);
					}
					if (igServerAddress.contains("tile"))
					{
						// mServerLayer.setMapServerByType(MapServerType.MapGISIGSServerTile);
						MapServer mapServer = mServerLayer.createMapServerByType(MapServerType.MapGISIGSServerTile);
						mapServer.setName("tile");
						mServerLayer.setMapServer(mapServer);
					}
					mServerLayer.setURL(igServerAddress);
					// 在渲染线程中setMap只能使用异步方法，mMapView.setMap(mServerMap);
					mMapView.setMapAsync(mServerMap, new MapViewFinishCallback()
					{
						@Override
						public void onDidFinish(boolean success)
						{
							IsloadMapFinish = success;
							mMapView.forceRefresh();
						}
					});
				}
			});
		}
		else if (mapType == ONLINEMAP && StringUtils.isNotEmpty(mMapInfo.getMapServerType()))
		{
			this.runOnUiThread(new Runnable()
			{
				@Override
				public void run()
				{
					DialogUtil.showProgressDlg(MapActivity.this, "正在加载在线地图");
				}
			});
			// 加载第三方在线地图
			final Enumeration enumeraiton = MapServerType.parse(MapServerType.class, mMapInfo.getMapServerType());
			mMapView.stopCurRequest(new MapViewStopCurRequestCallback()
			{
				@Override
				public void onDidStopCurRequest()
				{
					MapServer mapServer = mServerLayer.createMapServerByType((MapServerType) enumeraiton);
					mapServer.setName(enumeraiton.name());
					mServerLayer.setName(mMapInfo.getMapServerType());
					mServerLayer.setMapServer(mapServer);
					mServerLayer.setURL(mMapInfo.getServerUrl());
					mServerLayer.setName(mMapInfo.getServerName());
					// 在渲染线程中setMap只能使用异步方法，mMapView.setMap(mServerMap);
					mMapView.setMapAsync(mServerMap, new MapViewFinishCallback()
					{
						@Override
						public void onDidFinish(boolean success)
						{
							IsloadMapFinish = success;
							DialogUtil.hidenThreadProgressDlg();
							removeAllFragments();
						}
					});
				}
			});
		}
		else
		{
			ToolToast.showShort("未找到地图");
		}

		//获取
		if(mMapView.getMap() != null)
		{
			mSRefData = mMapView.getMap().getSRSInfo();
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.changemap_iv:
			final MapManagerModuleFrag mapManagerFrag = new MapManagerModuleFrag();
			// super.popBackStack();
			addFragment(EnumViewPos.RIGHTCENTER, mapManagerFrag, mapManagerFrag.getName(), null);
			addFragBackListen(mapManagerFrag);
			break;
		case R.id.check_layer_iv:
			if (IsloadMapFinish)
			{
				LayerManagerFragment layerManagFrag = new LayerManagerFragment();
				// super.popBackStack();
				addFragment(EnumViewPos.RIGHTCENTER, layerManagFrag, layerManagFrag.getName(), null);
				addFragBackListen(layerManagFrag);
			}
			else
			{
				ToolToast.showShort("地图未加载完成");
			}

			break;
		case R.id.tools_channel:
			showTools();
			break;
		case R.id.map_search_channel:
			showSearchView();
			break;
		case R.id.more_channel:
			// startActivity(new Intent(getApplicationContext(),
			// AccountActivity.class));
			AnimationsToolsUtils.startAnimationsOut(mComposerButtonsWrapper, 300);
			AccountFrag accountFrag = new AccountFrag();
			addFragment(EnumViewPos.FULL, accountFrag, accountFrag.getName(), null);
			addFragBackListen(accountFrag);
			break;

		case R.id.zoomin_btn:
			mMapView.zoomIn(true);
			break;
		case R.id.zoomout_btn:
			mMapView.zoomOut(true);
			break;
		case R.id.locationbtn_imgv:
			// 暂时屏蔽（会导致百度定位服务停止）
			// locationService.stop();
			initLocation();
			locationService.start();// 定位SDK
			if (IsFirstClickLocation)
			{
				mLocationType = LOCATION_TYPE_MAP_FOLLOW;
				mLocationGraphicImage.setImage(mLocationBmpOne);
				// mLocationImv.setBackgroundResource(R.drawable.ico_location_2);
				mLocationImv.setBackground(getResources().getDrawable(R.drawable.ico_location_2));
				IsFirstClickLocation = false;
				mMapView.setSlopeAngle(0.0f, false);
			}
			else
			{
				mLocationType = LOCATION_TYPE_MAP_ROTATE;
				mLocationGraphicImage.setImage(mLocationBmpTwo);
				// mLocationImv.setBackgroundResource(R.drawable.ico_location_3);
				mLocationImv.setBackground(getResources().getDrawable(R.drawable.ico_location_3));
				IsFirstClickLocation = true;
				mMapView.setSlopeAngle(66.0f, false);
			}
			mMapView.setTouchListener(this);
			mMapView.refresh();
			break;
		default:
			break;
		}

	}

	/***
	 * 添加Fragment（实现抽象父类接口）
	 */

	@Override
	public void addFragment(EnumViewPos enumPos, BaseFragment frag, String strTag, ICallBack callback)
	{
		int parentResId = -1;
		switch (enumPos)
		{
		case TOP:
			parentResId = R.id.maintop_content;
			break;

		case RIGHTCENTER:
			parentResId = R.id.maplayer_content_layout;
			break;
		case FULL:
			parentResId = R.id.full_content;
			break;
		case BOTTOM:
			// 查询模块
		default:
			break;
		}

		if (parentResId < 1)
		{
			return;
		}

		// for(BaseFragment baseFrag : mfrags)
		// {
		// if(baseFrag.getName() == frag.getName())
		// {
		// continue;
		// }
		// if(baseFrag.getparentViewID() == parentResId)
		// {
		// hideFragment(baseFrag.getName(), null);
		// }
		// }

		if (!frag.isAdded())
		{
			addFragment(parentResId, frag, strTag, callback);
			mfrags.add(frag);
		}
		else if (frag.isHidden())
		{
			showFragment(strTag, callback);
		}

	}

	/**
	 * 添加Fragment返回监听
	 * 
	 * @param frag
	 */
	public void addFragBackListen(final BaseFragment frag)
	{
		this.addGoBackListener(new ICallBackGoBack()
		{
			@Override
			public int onCall(String str)
			{
				Log.d(TAG, "remove:" + frag.getName());
				removeFragment(frag.getName(), null);
				mMapBottomContent.setVisibility(View.VISIBLE);
				mMapRightContent.setVisibility(View.VISIBLE);
				return 1;
			}
		});
	}

	/**
	 * 移除当前所有的Fragment
	 */
	public void removeAllFragments()
	{
		if (mfrags.size() > 0)
		{
			for (int i = 0; i < mfrags.size(); i++)
			{
				removeFragment(mfrags.get(i).getName(), null);
			}
		}
		else
		{
			Log.d(TAG, "mfrags == 0");
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		 /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK)
		{
			if (requestCode == this.TracksRequestCode)
			{
				if (data != null && data.getSerializableExtra("trackset") != null)
				{
					// 移除所有Fragment
					removeAllFragments();
					HashSet<Track> trackSet = (HashSet<Track>) data.getSerializableExtra("trackset");
					for (Track track : trackSet)
					{
						// 将轨迹添加到地图上
						TracksHistoryFrag tracksHistoryFrag = new TracksHistoryFrag();
						Bundle bd = new Bundle();
						bd.putSerializable("track", track);
						tracksHistoryFrag.setArguments(bd);
						// addFragment(EnumViewPos.FULL, tracksHistoryFrag,
						// tracksHistoryFrag.getName(), null);
						// addFragBackListen(tracksHistoryFrag);
						addFragment(R.id.full_content, tracksHistoryFrag, tracksHistoryFrag.getName(), null);
						break;
					}

				}

			}

		}
	}

	/**
	 * 动画显示工具界面
	 */
	private void showTools()
	{
		super.popBackStack();
		AnimationsToolsUtils.initOffset(getApplicationContext());
		if (mIsShowTools)
		{
			AnimationsToolsUtils.startAnimationsIn(mComposerButtonsWrapper, 300);
		}
		else
		{
			AnimationsToolsUtils.startAnimationsOut(mComposerButtonsWrapper, 300);
		}
		mIsShowTools = !mIsShowTools;

		AnimationsToolsUtils.showToolFrag(this, mComposerButtonsWrapper);
	}

	/**
	 * 显示查询界面
	 */
	private void showSearchView()
	{
		AnimationsToolsUtils.startAnimationsOut(mComposerButtonsWrapper, 300);
		if (IsloadMapFinish)
		{
			if (MapLayerUtils.getAllVectorLayer(mMapView).size() > 0)
			{
				mMapBottomContent.setVisibility(View.GONE);
				mMapRightContent.setVisibility(View.INVISIBLE);
				SearchModuleFrag searchFrag = new SearchModuleFrag();
				super.popBackStack();
				addFragment(EnumViewPos.FULL, searchFrag, searchFrag.getName(), null);
				addFragBackListen(searchFrag);
			}
			else
			{
				View alertView = getLayoutInflater().inflate(R.layout.view_changemap_alertdialog, null);
				AlertDialog.Builder alertDialog = DialogUtil.createNobuttonDialog(this, null, null, alertView, null);
				final Dialog dialog = alertDialog.show();
				dialog.getWindow().setBackgroundDrawable(new ColorDrawable());
				Button changeBtn = (Button) alertView.findViewById(R.id.changgemap_btn);
				changeBtn.setOnClickListener(new OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						MapManagerModuleFrag mapManagerFrag = new MapManagerModuleFrag();
						addFragment(EnumViewPos.RIGHTCENTER, mapManagerFrag, mapManagerFrag.getName(), null);
						dialog.dismiss();
					}
				});
			}
		}
	}

	@Override
	public boolean goback()
	{
		if (mfrags.size() > 1)
		{
			// super.popBackStack();
		}
		if (mfrags.size() < 1)
		{
			mMapBottomContent.setVisibility(View.VISIBLE);
		}
		DialogUtil.createTwoButtonDialog(this, "确认离开？", "确认退出", null, null, "取消", "确认", null, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				finish();
			}
		}).show();
		return false;
	}

	/**
	 * 初始化定位信息
	 */
	public void initLocation()
	{
		// 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
		locationService = MapApplication.getApp().locationService;
		// 设置定位监听
		// mMyLocationListener = new MyLocationListener(locHander);
		locationService.registerListener(mLocationListener);
		// 设置定位参数
		// mOption = locationService.getDefaultLocationClientOption();
		// if (MapApplication.getApp().isIsRecodSetting())
		// {
		// mOption = locationService.getOption();
		// }
		// else
		// {
		// mOption = locationService.getDefaultLocationClientOption();
		// }
		// locationService.setLocationOption(mOption);
	}

	@Override
	public boolean mapViewTouch(MotionEvent event)
	{
		mLocationType = -1;
		IsFirstClickLocation = true;
		mLocationImv.setBackgroundResource(R.drawable.ico_location_1);
		mLocationGraphicImage.setImage(mLocationBmpOne);
		mMapView.setTouchListener(null);
		return false;
	}

	/*****
	 * 接收定位结果消息，并显示在地图上
	 * 
	 */
	private BDLocationListener mLocationListener = new BDLocationListener()
	{

		@Override
		public void onReceiveLocation(BDLocation location)
		{
			if (null != location && location.getLocType() != BDLocation.TypeServerError)
			{
				// if (mMapView.getMap() != null)
				if (IsloadMapFinish)
				{
					// 坐标转换
					SpaProjection spaProject = new SpaProjection();
					// 源是GPS的坐标系
					spaProject.setSourcePara(SRefData.getWGS84());
					// 目的是地图的坐标系
					if (mSRefData != null)
					{
						String name = mSRefData.getSRSName();
						spaProject.setDestinationPara(mSRefData);
					}
					// 设置三参数或七参数
					ElpTransParam param = new ElpTransParam();
					if (mConfigManager.getTransStr().equalsIgnoreCase("三参数"))
					{
						param.dx = mConfigManager.getDx();
						param.dy = mConfigManager.getDy();
						param.dz = mConfigManager.getDz();
					}
					if (mConfigManager.getTransStr().equalsIgnoreCase("七参数"))
					{
						param.dx = mConfigManager.getDx();
						param.dy = mConfigManager.getDy();
						param.dz = mConfigManager.getDz();
						param.wx = mConfigManager.getWx();
						param.wy = mConfigManager.getWy();
						param.wz = mConfigManager.getWz();
						param.dm = mConfigManager.getDm();
					}
					spaProject.setEllipTransParam(param);

					Dot LonlatDot = new Dot(location.getLongitude(), location.getLatitude());
					// Dot merctDot
					// =PointTransferUtil.Lonlat2Mercator(LonlatDot);
					// 判断是否是加密坐标
					Dot correctDot = new Dot(LonlatDot.x, LonlatDot.y);
					if (mConfigManager.getCoordType().equalsIgnoreCase("GPS"))
					{
						//暂时屏蔽（Old）
//						GPS gps = GPSUtil.gcj_To_Gps84(LonlatDot.y, LonlatDot.x);
//						correctDot = new Dot(gps.getWgLon(), gps.getWgLat());
						//GPS坐标转换
						CoordinateConvert coordinateConvert = new CoordinateConvert();
						coordinateConvert.setConvertParams(new CoordinateConvertParameter().setSrcCoordinateType(CoordinateType.GCJ02_LatLng).setDestCoordinateType(CoordinateType.GPS_LatLng));
						Dot convertDot  = coordinateConvert.convert(new Dot(correctDot.y, correctDot.x));
						correctDot = new Dot(convertDot.y, convertDot.x);
					}

					spaProject.projTrans(correctDot);
					if (mSRefData != null)
					{
						updateLocationImage(mSRefData, correctDot);
					}
					/**
					 * @content 解决加载IGServer在线地图，定位结果不准确问题（增加过滤条件）
					 * @author admin 2017-6-23 上午10:50:50
					 */
					else
					{
						mLocationGraphicImage.setPoint(new Dot(-2004026200000.0, -2004026200000.0));
					}

					// 没想明白，暂时屏蔽
					// if(mLocationGraphicImage.getIsDisposable())
					// {
					// mLocationGraphicImage = new GraphicImage();
					// mLocationGraphicImage.setImage(mLocationBmpOne);
					// mLocationGraphicImage.setPoint(new Dot(0.0, 0.0));
					// mLocationGraphicImage.setAnchorPoint(new PointF(0.5f,
					// 0.5f));
					// mMapView.getGraphicsOverlay().addGraphic(mLocationGraphicImage);
					// }

				}

			}
		}

	};

	/**
	 * 更新定位图标的位置及状态
	 * 
	 * @param sRefData
	 * @param correctDot
	 */
	private void updateLocationImage(SRefData sRefData, Dot correctDot)
	{
		if (mLocationType == LOCATION_TYPE_MAP_FOLLOW)
		{
			// 地图先北朝上
			mMapView.setRotateAngle(0.0f, true);
			mLocationImv.setBackgroundResource(R.drawable.ico_location_2);
			mLocationGraphicImage.setPoint(correctDot);
			mLocationGraphicImage.setRotateAngle(calRoateAngle(mCurrentRoateAngle));
			mMapView.panToCenter(correctDot, false);
			updateGraphicCircle(sRefData, correctDot, true);
		}

		else if (mLocationType == LOCATION_TYPE_MAP_ROTATE)
		{
			mMapView.setRotateAngle(0.0f, true);
			mLocationImv.setBackgroundResource(R.drawable.ico_location_3);
			mLocationGraphicImage.setPoint(correctDot);
			mLocationGraphicImage.setRotateAngle(0.0f);
			mMapView.setRotateCenter(correctDot);
			mMapView.setRotateAngle(-calRoateAngle(mCurrentRoateAngle), true);
			updateGraphicCircle(sRefData, correctDot, true);
			// 问题mMapView rotate和zoomToRange冲突
		}
		else
		{
			mLocationImv.setBackgroundResource(R.drawable.ico_location_1);
			mLocationGraphicImage.setPoint(correctDot);
			updateGraphicCircle(sRefData, correctDot, false);
		}
		mMapView.refresh();
	}

	/**
	 * 更新精度圈
	 * 
	 * @param sRefData
	 * @param correctDot
	 */
	private void updateGraphicCircle(SRefData sRefData, Dot correctDot, boolean bZoom)
	{
		mGraphicCircle.setCenterPoint(correctDot);

		if (bZoom)
		{
			if (sRefData.getSRSName().equalsIgnoreCase("WGS_84_MCT"))
			{
				mGraphicCircle.setRadius(100);
				mMapView.zoomToRange(new Rect(correctDot.x - 500, correctDot.y - 600, correctDot.x + 500, correctDot.y + 600), false);
			}
			else if (sRefData.getSRSName().equalsIgnoreCase("WGS_1984_Web_Mercator"))
			{
				mGraphicCircle.setRadius(100);
				mMapView.zoomToRange(new Rect(correctDot.x - 500, correctDot.y - 600, correctDot.x + 500, correctDot.y + 600), false);
			}
			else if (sRefData.getSRSName().equalsIgnoreCase("WGS_1984"))
			{
				mGraphicCircle.setRadius(0.005);
				mMapView.zoomToRange(new Rect(correctDot.x - 0.01, correctDot.y - 0.02, correctDot.x + 0.01, correctDot.y + 0.02), false);
				// mConfigManager.setCoordType("GPS");
				// mConfigManager.saveConfig();
			}
			else
			{
				mGraphicCircle.setRadius(0.000);
			}
		}

		mMapView.refresh();
	}

	/**
	 * 计算方向角
	 */
	private float calRoateAngle(float currentangle)
	{
		float angle = 0.0f;
		if (currentangle < 180)
		{
			angle = -currentangle;
		}
		else if (currentangle > 180)
		{
			angle = 360 - currentangle;
		}

		return angle;

	}

	@Override
	protected void onDestroy()
	{
		if (mLocationListener != null && locationService != null)
		{
			locationService.unregisterListener(mLocationListener); // 注销掉监听
			locationService.stop(); // 停止定位服务
		}
		if (mMyOrientationListenr != null)
		{
			mMyOrientationListenr.stop();
		}
		super.onDestroy();
	}

	@Override
	protected void onStart()
	{
		Log.d(TAG, "onStart() run!!");
		super.onStart();
	}

	@Override
	protected void onResume()
	{
		Log.d(TAG, "onResume() run!!");
		super.onResume();
	}

	// 由系统销毁一个Activity时，onSaveInstanceState() 会被调用,临时存储数据
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		Log.e(TAG, "onSaveInstanceState() run!!");
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		Log.e(TAG, "onRestoreInstanceState() run!!");
		super.onRestoreInstanceState(savedInstanceState);
	}

	@Override
	protected void onPause()
	{
		Log.d(TAG, "onPause() run!!");
		super.onPause();
	}

	@Override
	protected void onStop()
	{
		Log.d(TAG, "onStop() run!!");
		super.onStop();
	}

	@Override
	public void mapViewWillStartLoadingMap(MapView mapView, String strDocPath)
	{

	}

	@Override
	public void mapViewDidFinishLoadingMap(MapView mapView, String strDocPath)
	{
		IsloadMapFinish = true;
		removeAllFragments();
	}

	@Override
	public void mapViewDidFailLoadingMap(MapView mapView, String strDocPath)
	{

	}
	

	// 参数设置 activity 颜色
	public static void setWindowStatusBarColor(Activity activity, int colorResId)
	{

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
		{
			// 得到窗口
			Window window = activity.getWindow();
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			// 设置状态栏的颜色
			window.setStatusBarColor(activity.getResources().getColor(colorResId));
			// 设置底部的颜色
			window.setNavigationBarColor(activity.getResources().getColor(colorResId));
		}
	}
}
